<?php

$pathInfo = $_SERVER['PATH_INFO'] ?? null;
$install = new install();
if (empty($_SERVER['PATH_INFO'])) {

    include_once "install.html";
    exit();
}
if ('/login' === $pathInfo) {
    //数据库
    $data = file_get_contents('php://input');
    if (empty($data)) {
        $ret = $install->code(400, ['error_msg' => "请完善信息"]);
        exit($ret);
    }
    $data = json_decode($data, true);
    $dbServername = $data['db_servername'];
    $dbPort = $data['db_port'] ?: 3306;
    $dbUsername = $data['db_username'];
    $dbPassword = $data['db_password'];
    $dbDatabase = $data['db_database'];
    if (empty($dbServername) || empty($dbUsername) || empty($dbPassword) || empty($dbDatabase)) {

        $ret = $install->code(400, ['error_msg' => "请完善数据库连接信息"]);
        exit($ret);
    }

    //后台账号
    $adminUsername = $data['admin_username'];
    $adminPassword = $data['admin_password'];
    $mallId = $data['mall_id'];
    if (empty($dbUsername) || empty($dbPassword)) {

        $ret = $install->code(400, ['error_msg' => "请完善后台登录信息"]);
        exit($ret);
    }

    //redis
    $redisServername = $data['redis_servername'];
    $redisPort = $data['redis_port'] ?: 6379;
    $redisPassword = $data['redis_password'] ?: null;
    if (empty($dbUsername) || empty($dbPassword)) {

        $ret = $install->code(400, ['error_msg' => "请完善redis信息"]);
        exit($ret);
    }

    $data = [
        'db' => [
            'servername' => $dbServername,
            'port' => $dbPort,
            'username' => $dbUsername,
            'password' => $dbPassword,
            'database' => $dbDatabase,
        ],
        'admin' => [
            'username' => $adminUsername,
            'password' => hash('sha256', $adminPassword),
            'unpassword' => $adminPassword,
            'id' => $mallId
        ],
        'redis' => [
            'servername' => $redisServername,
            'port' => $redisPort,
            'password' => $redisPassword,
            'select'   => $data['redis_select'] ?? 1
         ]
    ];

    list($code, $data) = $install->setDb($data);

    if (200 !== $code) {
        $ret = $install->code($code, ['error_msg' => $data]);
        exit($ret);
    }

    $ret = $install->code($code, ['msg' => $data]);
    exit($ret);
}

class install
{

    //TODO 添加版本号
    public function setDb(array $data): array
    {

        //数据库名称

        try {
            $dbname = $data['db']['database'];//测试连接
            $conn = @new mysqli($data['db']['servername'], $data['db']['username'], $data['db']['password'], $data['db']['database'], $data['db']['port']);
            if ($conn->connect_error) {

                return [400, "数据库配置有误!!!"];
            }
            try {
                $redis = new \Redis();
            } catch (Exception $e) {
                return [400, "请根据操作手册安装Redis扩展"];
            }
            try {
                $redis->connect($data['redis']['servername'], $data['redis']['port'], 10);
                $redis->auth($data['redis']['password']);
                $redis->set('check', "check");
                $redis->del('check');
            } catch (\Exception $e) {
                return [400, "Redis配置错误！"];
            }
            $sqlData = file_get_contents("install.sql");
            $sqlData = str_replace(
                array("?jinzhe_mall?", "?admin_user?", "?admin_password?", "?admin_un_password?","?mall_id?", "?create_time?"),
                array(
                    $data['db']['database'],
                    $data['admin']['username'],
                    $data['admin']['password'],
                    $data['admin']['unpassword'],
                    $data['admin']['id'],
                    date('Y-m-d H:i:s', time())
                ),
                $sqlData
            );
            $sqlList = explode(";", $sqlData);

            foreach ($sqlList as $sql) { //遍历数组
                if (empty($sql))
                    continue;
                $sql .= ";";
                $conn->query($sql);
            }
//            $flag = $conn->multi_query($sqlData);
//            if (!$flag) {
//                return [400, "数据库创建失败!!!"];
//            }
            $conn->close();//修改env配置文件
            $env = <<<EOF
CHECKDB = 1
PROFILES = pro
[APP]
DEFAULT_TIMEZONE = Asia/Shanghai

[DATABASE]
TYPE = mysql
HOSTNAME = [HOSTNAME]
DATABASE = [DBDATABASE]
USERNAME = [USERNAME]
PASSWORD = [PASSWORD]
HOSTPORT = [PORT]
CHARSET = utf8
PREFIX = jiecheng_
PREFIX_SAAS = jiecheng_saas_

[REDIS]
HOST = [REDISHOST]
REDISPORT = [REDISPORT]
REDISPASSWORD = [REDISPASSWORD]
SELECT = [REDISSELECT]

[LANG]
default_lang = zh-cn
EOF;
            $env = str_replace(
                array(
                    "[HOSTNAME]",
                    "[USERNAME]",
                    "[PASSWORD]",
                    "[DBDATABASE]",
                    "[PORT]",
                    "[REDISHOST]",
                    "[REDISPORT]",
                    "[REDISPASSWORD]",
                    "[REDISSELECT]"
                ),
                array(
                    $data['db']['servername'],
                    $data['db']['username'],
                    $data['db']['password'],
                    $dbname,
                    $data['db']['port'],
                    $data['redis']['servername'],
                    $data['redis']['port'],
                    $data['redis']['password'] ?: "",
                    $data['redis']['select'] ?? 1
                ),
                $env
            );//执行脚本
            file_put_contents("../.env", $env);
            $installSh = file_get_contents("install.sh");
            $installSh = str_replace("[ROOT_PATH]", __DIR__, $installSh);
            $projectPath = substr(__DIR__, 0, -7);
            $installSh = str_replace("[PROJECT_PATH]", $projectPath, $installSh);
            file_put_contents("install.sh", $installSh);
        } catch (\Exception $e) {
            return [$e->getCode(), $e->getMessage()];
        }

        //删除sql文件和脚本
        unlink("install.sql");
        //unlink("install.sh");
        unlink("install.php");
        unlink("install.html");


        return [200, "创建成功!!!"];
    }


    public function code($code, $data)
    {
        return json_encode(["code" => $code, "data" => $data]);
    }

}